package com.talkyun.utils.loader;

import com.talkyun.utils.json.JSON;
import com.talkyun.utils.json.JSONObject;
import com.talkyun.utils.loader.impl.DiskStore;
import com.talkyun.utils.loader.impl.HttpLoader;

import java.io.IOException;

import static com.talkyun.utils.MD5.md5;

public class MixLoader {
    private DiskStore diskStore;
    private HttpLoader httpLoader;

    public MixLoader(String id, String url) {
        this(id, url, 1000);
    }

    public MixLoader(String id, String url, int timeout) {
        this.httpLoader = new HttpLoader(url, timeout);
        this.diskStore = new DiskStore("loader-" + id + "-" + md5(url));
    }

    public JSONObject load() {
        return load(3);
    }

    public JSONObject load(int num) {
        return load(null, num);
    }

    public JSONObject load(String form) {
        return load(form, 3);
    }


    public JSONObject load(String form, int num) {
        // First: load from http
        for (int i = 0; i < num; i++) {
            try {
                String json = httpLoader.load(form);
                if (json != null) {
                    this.store(json);
                    return this.decode(json);
                }
            } catch (IOException e) {
                this.sleep(1000);
            } catch (Throwable t) {
                this.sleep(1000);
                t.printStackTrace(System.err);
            }
        }

        System.err.println("Error load from url, from local file !!!");
        // Second: load from disk
        for (int j = 0; j < num; j++) {
            try {
                String json = diskStore.load();
                if (json != null) {
                    return this.decode(json);
                }
            } catch (Throwable t) {
                this.sleep(500);
            }
        }
        // Last: null, throw exception
        throw new RuntimeException("Can't load by url and file!");
    }

    private void store(String text) {
        try {
            diskStore.store(text);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }

    private JSONObject decode(String json) {
        return JSON.parseObject(json);
    }

    private void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    public static void main(String[] args) {
        MixLoader loader = new MixLoader("test", "https://openx.oss-cn-shenzhen.aliyuncs.com/data/status.json", 3000);
        System.out.println(loader.load());
    }
}